package cn.com.chengmandian.core.web.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context = null;

    private static final String DEV = "dev";
    private static final String PRD = "prd";

    private static final String SPRING_APPLICATION_NAME = "spring.application.name";

    public static <T> T getBean(Class<T> clz) throws BeansException {
        return (T)context.getBean(clz);
    }

    public static Object getBean(String name) throws BeansException {
        return context.getBean(name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 判断是否是测试环境
     * @return
     */
    public static boolean isDev() {
        try {
            return context.getEnvironment().getActiveProfiles()[0].equals(DEV);
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 获取环境参数
     * @return
     */
    public static String getEnv() {
        try {
            return context.getEnvironment().getActiveProfiles()[0];
        } catch (Exception e) {
            return "UnKnow";
        }
    }

    public static boolean isPrd() {

        try {
            return context.getEnvironment().getActiveProfiles()[0].equals(PRD);
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 获取应用名称
     * @return
     */
    public static String getAppName() {
        return context.getEnvironment().getProperty(SPRING_APPLICATION_NAME);
    }
}
